package com.lsz.intelligentflowerwatering

import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.location.LocationManager
import android.util.Log
import com.lsz.intelligentflowerwatering.ui.toast
import com.lsz.intelligentflowerwatering.viewmodel.BleState
import com.lsz.intelligentflowerwatering.viewmodel.BleViewModel
import com.lsz.intelligentflowerwatering.viewmodel.MainViewModel

class MainBroadcastReceiver(private val mainViewModel: MainViewModel,private val bleViewModel: BleViewModel) : BroadcastReceiver() {

    //！！！防止多次响应广播，定位收到多次响应的原因还没发现，蓝牙就没有这样的问题
    private var locationEnable = false

    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        context?.let {
            if (action == BluetoothAdapter.ACTION_STATE_CHANGED) {
                when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
                    BluetoothAdapter.STATE_OFF -> {
                        toast(context, "蓝牙已关闭，请打开蓝牙")
                        bleViewModel.bleState = BleState.ScanEnd
                    }
                    BluetoothAdapter.STATE_ON -> {
                        toast(context, "蓝牙已打开")
                        bleViewModel.bleState = BleState.ScanFail
                    }
                }
            }
            if (action == LocationManager.PROVIDERS_CHANGED_ACTION) {
                Log.i("定位响应", "location changed")
                val locationManager =
                    context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
                // 判断GPS是否可用
                val isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
                if (isGpsEnabled) {
                    if (!locationEnable){
                        locationEnable = true
                        toast(context, "定位已打开")
                        bleViewModel.bleState = BleState.ScanEnd

                    }
                } else {
                    if (locationEnable){
                        locationEnable = false
                        toast(context, "定位已关闭，请打开定位")
                    }
                    bleViewModel.bleState = BleState.ScanFail
                }
            }
        }
    }
}